package org.lilystudio.veryftp.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.lilystudio.veryftp.dao.GenericDAO;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class GenericSpringHibernateDAO<T, ID extends Serializable> 
		extends HibernateDaoSupport implements GenericDAO<T, ID> {


	private Class<T> persistentClass;

	@SuppressWarnings("unchecked")
	public GenericSpringHibernateDAO() {
		this.persistentClass = (Class<T>) ((ParameterizedType) (getClass()
				.getGenericSuperclass())).getActualTypeArguments()[0];
	}

	public Class<T> getPersistentClass() {
		return persistentClass;
	}

	@SuppressWarnings("unchecked")
	public List<T> findAll() {
		return getHibernateTemplate().loadAll(getPersistentClass());
	}

	@SuppressWarnings("unchecked")
	public List<T> findByExample(T exampleInstance) {
		return getHibernateTemplate().findByExample(exampleInstance);
	}

	@SuppressWarnings("unchecked")
	public T findById(ID id) {
		Object entity = getHibernateTemplate().get(getPersistentClass(), id);
		return (T) entity;
	}

	public void save(T entity) {
		getHibernateTemplate().saveOrUpdate(entity);
	}

	public void delete(T entity) {
		getHibernateTemplate().delete(entity);
	}

	/**
	 * @param namedQuery
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<T> findByNamedQuery(final String namedQuery) {
		return getHibernateTemplate().findByNamedQuery(namedQuery);
	}

	/**
	 * @param query
	 * @param parameter
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<T> findByNamedQuery(final String query, final Object parameter) {
		return getHibernateTemplate().findByNamedQuery(query, parameter);
	}

	/**
	 * @param query
	 * @param parameters
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<T> findByNamedQuery(final String query,
			final Object[] parameters) {
		return getHibernateTemplate().findByNamedQuery(query, parameters);
	}

	/**
	 * @param query
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<T> find(final String query) {
		return getHibernateTemplate().find(query);
	}

	/**
	 * @param query
	 * @param parameter
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<T> find(final String query, final Object parameter) {
		return getHibernateTemplate().find(query, parameter);
	}

	public void merge(T entity) {
		 getHibernateTemplate().merge(entity);
	}
}
